<template>
  <div class="api-key-container">
    <!-- 触发按钮 -->
    <el-button
      type="primary"
      text
      bg
      @click="dialogVisible = true"
      icon="Key"
    >
      API密钥配置
    </el-button>

    <!-- 密钥配置弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="API密钥管理"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <!-- 密钥显示区域 -->
        <div v-if="apiKey" class="key-display">
          <div class="key-content">
            <span class="key-text">{{ maskedKey }}</span>
            <button
              class="copy-btn"
              @click="copyKey"
              title="复制密钥"
            >
              <i class="fa-regular fa-copy"></i>
            </button>
          </div>
          <p class="key-desc">
            请妥善保管您的API密钥，它用于访问数据集相关接口。
            <span class="text-danger">请勿泄露给无关人员！</span>
          </p>
        </div>

        <!-- 无密钥状态 -->
        <div v-else class="no-key">
          <p>您尚未生成API密钥，请点击下方按钮生成</p>
        </div>
      </div>

      <template #footer>
        <el-button
          type="primary"
          @click="handleGenerateKey"
          :loading="loading"
        >
          <i class="fa-solid fa-key"></i>
          {{ apiKey ? '重新生成密钥' : '生成API密钥' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { getCurrentKey, generateKey, updateKey } from '@/api/base/search/datasetClient'
import { ElMessage, ElButton, ElDialog } from 'element-plus'

// 状态管理
const dialogVisible = ref(false) // 弹窗显示状态
const apiKey = ref('') // 实际密钥
const loading = ref(false) // 加载状态

// 监听弹窗显示，加载密钥
watch(dialogVisible, (newVal) => {
  if (newVal) {
    fetchCurrentKey()
  }
})

// 初始化时预加载一次（可选，也可仅在弹窗打开时加载）
onMounted(() => {
  fetchCurrentKey()
})

// 获取当前用户密钥
const fetchCurrentKey = async () => {
  try {
    loading.value = true
    const res = await getCurrentKey()
    if (res.code === 200) {
      apiKey.value = res.data || ''
    } else {
      ElMessage.error('获取密钥失败：' + res.msg)
    }
  } catch (err) {
    console.error('获取密钥异常：', err)
    ElMessage.error('获取密钥失败，请刷新页面重试')
  } finally {
    loading.value = false
  }
}

// 生成/重新生成密钥
const handleGenerateKey = async () => {
  try {
    loading.value = true
    // 如果已有密钥则调用更新接口，否则调用生成接口
    const res = apiKey.value ? await updateKey() : await generateKey()

    if (res.code === 200) {
      apiKey.value = res.data
      ElMessage.success(apiKey.value ? '密钥重新生成成功' : '密钥生成成功')
    } else {
      ElMessage.error('操作失败：' + res.msg)
    }
  } catch (err) {
    console.error('密钥操作异常：', err)
    ElMessage.error('操作失败，请重试')
  } finally {
    loading.value = false
  }
}

const copyKey = async () => {
  if (!apiKey.value) return;
  try {
    await navigator.clipboard.writeText(apiKey.value);
    ElMessage.success('密钥已复制到剪贴板');
  } catch (err) {
    // 回退方案（兼容旧浏览器）
    const ta = document.createElement('textarea');
    ta.value = apiKey.value;
    ta.setAttribute('readonly', '');
    ta.style.position = 'absolute';
    ta.style.left = '-9999px';
    document.body.appendChild(ta);
    ta.select();
    try {
      document.execCommand('copy');
      ElMessage.success('密钥已复制到剪贴板');
    } catch (e) {
      ElMessage.error('复制失败，请手动复制');
    } finally {
      document.body.removeChild(ta);
    }
  }
}

// 掩码显示（只显示前4位和后4位）
const maskedKey = computed(() => {
  if (!apiKey.value) return ''
  if (apiKey.value.length <= 8) return apiKey.value
  return apiKey.value.slice(0, 8) + '****' + apiKey.value.slice(-8)
})
</script>

<style lang="scss" scoped>
// 变量定义
$border-color: #e5e7eb;
$border-radius: 8px;
$shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
$primary-color: #3b82f6;
$primary-hover: #2563eb;
$primary-disabled: #93c5fd;
$text-muted: #6b7280;
$text-danger: #ef4444;
$bg-light: #f9fafb;

.api-key-container {
  display: inline-block; // 确保按钮只占自身宽度
}

.dialog-content {
  padding: 10px 0;
}

.key-display {
  margin-bottom: 20px;

  &-content {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    background-color: $bg-light;
    border: 1px solid $border-color;
    border-radius: 6px;
  }

  &-text {
    flex: 1;
    word-break: break-all;
    font-family: monospace;
    color: #111827;
  }

  &-desc {
    margin: 8px 0 0;
    font-size: 14px;
    color: $text-muted;
  }
}

.copy-btn {
  padding: 4px 8px;
  background: none;
  border: none;
  color: $primary-color;
  cursor: pointer;
  transition: color 0.2s;

  &:hover {
    color: $primary-hover;
  }

  i {
    font-size: 16px;
  }
}

.no-key {
  margin-bottom: 20px;
  padding: 16px;
  text-align: center;
  color: $text-muted;
  border: 1px dashed $border-color;
  border-radius: 6px;
}

.text-danger {
  color: $text-danger;
}
</style>